# -*-* encoding:UTF-8 -*-
# author            : mengy
# date              : 2019/2/12
# python-version    : Python 3.7.0
# description       : 获取数据库评论信息

import os, uuid
from com.articles.microapp.utils.logger_utils import Logger
from com.articles.microapp.utils.xml_utils import XMLParser
from com.articles.microapp.utils.db_utils import DbUtils
from com.articles.microapp.utils.constants import CommonConstants
from com.articles.microapp.utils.string_utils import String
from com.articles.microapp.utils.cache_utils import Cache
from com.articles.microapp.entities.remark import Remark

logger = Logger()
consts = CommonConstants()


class RemarkDao(object):
    __XMLParser = XMLParser(file=os.path.dirname(os.path.realpath(__file__)) + '\\remark_dao.xml')
    __DbUtils = DbUtils.db_util()
    __Cache = Cache()

    def get_remarks(self, article_id, user_id, page=[consts.DEFAULT_PAGE_NO, consts.DEFAULT_PAGE_SIZE]):
        try:
            if String.is_empty(article_id):
                raise Exception('文章ID不能为空！')
            sql = self.__XMLParser.get_sql('getRemarkByArtId', params={'articleId': article_id}, page=page)
            sql = str.replace(sql, '?', user_id)
            remarks = []
            results = self.__DbUtils.selectall(sql)
            for result in results:
                remark = Remark(**result)
                remark.user = self.__Cache.get_user(remark.userId).__dict__
                remarks.append(remark.__dict__)
            qry_count = self.__XMLParser.get_sql('getRemarkTotal', params={'articleId': article_id})
            total = self.__DbUtils.selectone(qry_count)['total']
            return {
                "list": remarks,
                "total": total
            }
        except Exception as e:
            logger.error('获取文章评论失败，%s', e)

    def add_remark(self, article_id, user_id, content):
        try:
            if String.is_empty(article_id) or String.is_empty(user_id) or String.is_empty(content):
                raise Exception('缺少必要参数')
            sql = self.__XMLParser.get_sql('addRemark', (uuid.uuid4(), article_id, user_id, content))
            return self.__DbUtils.insert(sql)
        except Exception as e:
            logger.error('添加评论失败！%s', e)
            return False

    def is_locked(self, id, user_id):
        try:
            if String.is_empty(id) or String.is_empty(user_id):
                raise Exception('缺少必要参数！')
            sql = self.__XMLParser.get_sql('checkIsPraise', params={'id': id, 'userId': user_id})
            is_locked = self.__DbUtils.selectone(sql)
            return bool(is_locked['isLocked'])
        except Exception as e:
            logger.error('查询是否点赞失败，%s', e)
        return None

    def add_like(self, obj_id, user_id):
        try:
            if String.is_empty(obj_id) or String.is_empty(user_id):
                raise Exception('缺少必要参数！')
            sql = self.__XMLParser.get_sql('addLike', params=(obj_id, user_id))
            return self.__DbUtils.insert(sql)
        except Exception as e:
            logger.error('点赞异常，', e)
            return False

    def cancel_like(self, obj_id, user_id):
        try:
            if String.is_empty(obj_id) or String.is_empty(user_id):
                raise Exception('缺少必要参数！')
            sql = self.__XMLParser.get_sql('cancelLike', params={'id': obj_id, 'userId': user_id})
            return self.__DbUtils.delete(sql)
        except Exception as e:
            logger.error('取消点赞异常，', e)
            return False


if __name__ == '__main__':
    remark = RemarkDao()
    # print(remark.get_remarks('e32f7e76-23a7-11e9-bdea-bcee7b12245f', '28045612534', page=[0, 20]))
    print(remark.add_remark('e32f7e76-23a7-11e9-bdea-bcee7b12245f', '28056489752', 'content'))
